local socket = require "skynet.socket"
local message_packet = require "common.message_packet"
local msg_center = require "race.msg_center"
local service_helper = require "common.service_helper"
local MessageType = require "common.message_type"

local Player = {}

Player.State = {
    None = 0,
    Online = 1,
    Offline = 2,
}

function Player:new(open_id,room_id,index,token)
    local o = {
        open_id = open_id or "",
        room_id = room_id or 0,
        index = index or 0,
        token = token or "",
        state = Player.State.None,
        socket_ = nil,
        userData_ = nil,
    }
    setmetatable(o,self)
    self.__index = self
    return o
end

function Player:getIndex()
    return self.index
end

function Player:getFd()
    return self.socket_
end

function Player:getOpenID()
    return self.open_id
end

function Player:getRoomID()
    return self.room_id
end

function Player:setUserData(d)
    self.userData_ = d
end

function Player:getUserData()
    return self.userData_
end

function Player:getToken()
    return self.token
end

function Player:checkToken(token)
    token = token or ""
    return self.token == token
end

function Player:onOnline(sock)
    self.socket_ = sock
    self.state = Player.State.Online
end

function Player:onOffline()
    self.socket_ = nil
    self.state = Player.State.Offline
end

function Player:isOnline()
    return Player.State.Online == self.state
end

function Player:isReady()
    return Player.State.None ~= self.state
end

function Player:sendUdpRawMessage(buf)

    if self.socket_ then
        socket.sendto(msg_center.getListenId(),self.socket_,buf)
        return true
    end

    return false
end

function Player:sendUdpMessage(id,t,message)

    if self.socket_ then
        local pack = message_packet.packSendBuffer(id,t,message)
        socket.sendto(msg_center.getListenId(),self.socket_,pack)
        return true
    end

    return false

end

function Player:sendTcpMessage(id,t,msg)

    local data = {
        open_ids = {self.open_id},
        message_id = id,
        message_type = t,
        msg = msg,
    }

    service_helper.send2Agent(MessageType.Forward2Client,data)

end

return Player